package com.easyfun.healthmagicbox.comm;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.content.Context;
import android.util.Log;

import com.easyfun.healthmagicbox.pojo.ConstantData;
import com.easyfun.healthmagicbox.sync.CommCallback;

public abstract class BaseCommTask  implements Runnable{
	int tmout = 15;

	protected Context mcontext;
	protected CommCallback ccb;
	 
	public BaseCommTask(Context mcontext,CommCallback ccb)
	{
		this.mcontext = mcontext;
		this.ccb = ccb;
		//before run this task, make its waiting
		this.ccb.initialStatus();
	}
	
	private final static String TAG = BaseCommTask.class.getSimpleName();

	protected String uploadByHTTP(Map<String, String> parmas, String relativeURL)
			throws ClientProtocolException, IOException {
		return uploadByHTTP(parmas, relativeURL, 0);

	}

	protected String uploadByHTTP(Map<String, String> parmas,
			String relativeURL, int requestTimeOut)
			throws ClientProtocolException, IOException {

		if (requestTimeOut > 0) {
			tmout = requestTimeOut;
		}

		ArrayList<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
		if (parmas != null) {
			Set<String> keys = parmas.keySet();
			for (Iterator<String> i = keys.iterator(); i.hasNext();) {
				String key = (String) i.next();
				pairs.add(new BasicNameValuePair(key, parmas.get(key)));
			}
		}
		UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(pairs, "UTF-8");

		HttpPost httppost = new HttpPost(ConstantData.getServerURL(mcontext) + relativeURL);
		// httppost.addHeader("Authorization", "your token"); //认证token
		//httppost.addHeader("Content-Type", "application/json");
		httppost.addHeader("Cache-Control", "NO-CACHE");
		HttpParams httpParams = new BasicHttpParams();

		httpParams.setParameter("charset", "UTF-8");
		HttpConnectionParams.setConnectionTimeout(httpParams, tmout * 1000); // 毫秒
		HttpConnectionParams.setSoTimeout(httpParams, tmout * 1000);

		// params.setParameter("jsonstring", entity);
		/*
		 * 将POST数据放入HTTP请求
		 */
		httppost.setEntity(p_entity);

		 httppost.setParams(httpParams);
		// httppost.setEntity(entity);
		HttpClient httpClient = new DefaultHttpClient();

		// HttpHost proxy = new HttpHost("wwwgate0-ch.mot.com", 1080);
		// hc.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
		// proxy);

		HttpResponse resp = httpClient.execute(httppost);
		

		//BufferedReader reader = new BufferedReader(new InputStreamReader(
		//		resp.getEntity().getContent(), "UTF-8"));
		HttpEntity entity = resp.getEntity();
		InputStream inputStream = entity.getContent();
		   BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
		   String json = "";
		   String line = "";
		   while((line = reader.readLine()) != null){
			   json = json + line;
		   }
		return json;
			

	}

	/*
	public static String loadManySerialized(String relativeURL) {
		HttpClient httpclient = new DefaultHttpClient();

		// Prepare a request object
		HttpGet httpget = new HttpGet(ConstantData.ServerURL + relativeURL);

		// Execute the request
		HttpResponse response;

		String result = null;
		try {
			response = httpclient.execute(httpget);

			// Get hold of the response entity
			HttpEntity entity = response.getEntity();
			// If the response does not enclose an entity, there is no need
			// to worry about connection release

			if (entity != null) {
				// A Simple Response Read
				InputStream instream = entity.getContent();
				result = convertStreamToString(instream);

				// Closing the input stream will trigger connection release
				instream.close();
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return result;
	}
	*/
	private static String convertStreamToString(InputStream is) {
		/*
		 * To convert the InputStream to String we use the
		 * BufferedReader.readLine() method. We iterate until the BufferedReader
		 * return null which means there's no more data to read. Each line will
		 * appended to a StringBuilder and returned as String.
		 */
		BufferedReader reader = new BufferedReader(new InputStreamReader(is),
				8192);
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return sb.toString();
	}

	
	
}
